package org.dragon.commons;

/**
 * Author:     Zhao Yan
 * DateTime:   2023/5/17 10:12
 */

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

public interface Web {

    static void write(HttpServletResponse response, String content) {
        write(response, content, HttpStatus.OK);
    }

    static void write(HttpServletResponse response, String content, HttpStatus status) {
        response.setHeader(Const.CONTENT_TYPE, MediaType.TEXT_HTML_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setStatus(status.value());

        try (PrintWriter writer = response.getWriter()) {
            writer.write(content);
        } catch (IOException e) {
            throw new ApplicationException(Errors.InvalidOperation, e.getMessage());
        }
    }

    static void write(HttpServletResponse response, Object content) {
        write(response, content, HttpStatus.OK);
    }

    static void write(HttpServletResponse response, Object content, HttpStatus status) {
        response.setHeader(Const.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setStatus(status.value());

        try (PrintWriter writer = response.getWriter()) {
            writer.write(new ObjectMapper().writeValueAsString(content));
        } catch (IOException e) {
            throw new ApplicationException(Errors.InvalidOperation, e.getMessage());
        }
    }

    static String getToken(HttpServletRequest request) {
        return request.getHeader(Const.AUTHORIZATION);
    }

    static boolean match(String pattern, String value) {
        return new AntPathMatcher().match(pattern, value);
    }
}